package Buildings.threads;
public class ElementalSemaphore {
    private Object source;
    private boolean occup;
    private Thread prev;
    private Thread proc;
    
    synchronized public Object getObj(){
        return source;
    }
    public ElementalSemaphore(Object o){
        source=o;
        occup=false;
        prev=null;
        proc=null;
    }
    
    public void enter(){
        synchronized(source){
        while(occup || Thread.currentThread()==prev)
            try {
            source.wait();
        } catch (InterruptedException e) {
            System.out.println("Поток "+ Thread.currentThread()+" прерван");
        }
        occup=true;
        proc=Thread.currentThread();
        }
    }
    public void leave(){
        try{
        if(Thread.currentThread()!=proc)throw new IllegalArgumentException();
        synchronized(source){
        prev=Thread.currentThread();
        occup=false;
        source.notifyAll();}
        }catch(IllegalArgumentException e){
            System.out.println("Поток не входил в семафор!");
            Thread.currentThread().interrupt();
        }
    }   
}
